//
//  MHTheLoaiViewController.m
//  MHO
//
//  Created by papo on 2/17/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHTheLoaiViewController.h"
#import "Contants.h"
#import "TTScrollSlidingPagesController.h"
#import "TTSlidingPage.h"
#import "TTSlidingPageTitle.h"
#import "Group.h"
#import "Lib.h"
#import "GroupView.h"
#import "MHBaseViewController.h"
#import "MHAppListViewController.h"
#import "MHAppDelegate.h"

@interface MHTheLoaiViewController ()
{
    BOOL appFirstLoad, gameFirstLoad, gameOnlineFirstLoad;
    NSString*   groupId;
}

@property (strong, nonatomic) TTScrollSlidingPagesController *mySlider;

@property (nonatomic, weak) IBOutlet UITableView* tableView;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *buttonApp;
@property (weak, nonatomic) IBOutlet UIButton *buttonGame;
@property (weak, nonatomic) IBOutlet UIButton *buttonGameOnline;

@property (nonatomic, strong) MHNavibarView* navibarView;

@property (strong, nonatomic) IBOutlet UITableViewController *appTableView;
@property (strong, nonatomic) IBOutlet UITableViewController *gameTableView;
@property (strong, nonatomic) IBOutlet UITableViewController *gameOnlineTableView;
@end

@implementation MHTheLoaiViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navibarView = [MHNavibarView createWithLeftButton:kFileBtnHuman rightButton:nil searchButton:YES];
    [self.navibarView setActionSelectorDelegate:self left:@selector(leftButtonPressed:) right:nil search:nil];
    [self.navibarView setRootViewController:self];
    [self.view addSubview:self.navibarView];

    //initial setup of the TTScrollSlidingPagesController.
    self.mySlider = [[TTScrollSlidingPagesController alloc] init];

    //set properties to customiser the slider. Make sure you set these BEFORE you access any other properties on the slider, such as the view or the datasource. Best to do it immediately after calling the init method.
    //self.slider.hideStatusBarWhenScrolling = YES;
    self.mySlider.titleScrollerHidden = YES;
    //slider.titleScrollerHeight = 100;
    //slider.titleScrollerItemWidth=60;
    //slider.titleScrollerBackgroundColour = [UIColor darkGrayColor];
    //slider.disableTitleScrollerShadow = YES;
    self.mySlider.disableUIPageControl = YES;
    //slider.initialPageNumber = 1;
    //slider.pagingEnabled = NO;
    //slider.zoomOutAnimationDisabled = YES;

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7){
        self.mySlider.hideStatusBarWhenScrolling = YES;//this property normally only makes sense on iOS7+. See the documentation in TTScrollSlidingPagesController.h. If you wanted to use it in iOS6 you'd have to make sure the status bar overlapped the TTScrollSlidingPagesController.
    }

    //set the datasource.
    self.mySlider.dataSource = self;
    self.mySlider.delegate = self;

    //add the slider's view to this view as a subview, and add the viewcontroller to this viewcontrollers child collection (so that it gets retained and stays in memory! And gets all relevant events in the view controller lifecycle)
    CGRect frame = self.view.frame;
    frame.origin.y += self.topView.frame.size.height + self.navibarView.frame.size.height;
    frame.size.height -= (self.topView.frame.size.height + self.navibarView.frame.size.height);
    self.mySlider.view.frame = frame;
    [self.view addSubview:self.mySlider.view];
    [self addChildViewController:self.mySlider];

    [self gameButtonPressed: nil];

    [self.view setBackgroundColor:[UIColor whiteColor]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self refresh];
}

- (void)leftButtonPressed:(id)sender {
    [[MHAppDelegate sharedApp].viewController showLeftPanelAnimated:YES];
}

- (void)refresh {
    [Lib showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.data = [Group getAllGroupsSystem:groupId];
        // main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            [self stopLoadingMore];
            [self stopLoading];
            [self.tableView reloadData];
        });
    });
}

#pragma mark - UITableView Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count;
    if (section == 1) {
       count = round(self.data.count / 2);
    }else {
        count = 0;
    }

    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 120;
    }
    else {
        return 69;
    }
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* cellIdentifier = @"Cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    NSInteger index = indexPath.row * 2;
    if (!cell) {
        cell = [[UITableViewCell alloc] init];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        if (indexPath.section == 1) {
            if (index < self.data.count) {
                GroupView* view1 = [GroupView viewFromNib];
                [view1 setTag:1];
                [view1 setFrame:CGRectMake(0, 0, 155, 70)];
                [cell.contentView addSubview:view1];
            }
            if (index + 1 < self.data.count) {
                GroupView* view2 = [GroupView viewFromNib];
                [view2 setTag:2];
                [view2 setFrame:CGRectMake(160, 0, 155, 70)];
                [cell.contentView addSubview:view2];
            }
        }
    }

    if (indexPath.section == 1) {
        for (int i = 0; i < 2; i++) {
            GroupView* view = (GroupView*)[cell.contentView viewWithTag:i + 1];
            [view setDelegate:self];
            [view setIndexPath:indexPath];
            if (view && index + i < self.data.count) {
                Group* group = (Group*)self.data[index + i];
                if (group) {
                    [view setGroup:group];
                }
            }
        }
    }

    return cell;
}
#pragma mark - UITableview Delegate


#pragma mark TTSlidingPagesDataSource methods
-(NSInteger)numberOfPagesForSlidingPagesViewController:(TTScrollSlidingPagesController *)source{
    return 3;
}

-(TTSlidingPage *)pageForSlidingPagesViewController:(TTScrollSlidingPagesController*)source atIndex:(NSInteger)index{
    UIViewController *viewController;
    if (index == 1) {
        viewController = self.appTableView;
    }
    else if (index == 0) {
        viewController = self.gameTableView;
    }
    else {
        viewController = self.gameOnlineTableView;
    }
    CGRect frame = self.mySlider.view.frame;
    frame.origin.y = 0;
    //    frame.size.height -= self.topView.frame.size.height;
    [viewController.view setFrame:frame];

    return [[TTSlidingPage alloc] initWithContentViewController:viewController];
}

-(TTSlidingPageTitle *)titleForSlidingPagesViewController:(TTScrollSlidingPagesController *)source atIndex:(NSInteger)index{
    TTSlidingPageTitle *title;
    if (index == 0){
        //use a image as the header for the first page
        title= [[TTSlidingPageTitle alloc] initWithHeaderText:@"Top App"];
    } else {
        //all other pages just use a simple text header
        title = [[TTSlidingPageTitle alloc] initWithHeaderText:@"Top Game"];

    }
    return title;
}

////The below method in the datasource might get removed from the control some time in the future as it doesn't work that well with the headers if the width is small.
//-(int)widthForPageOnSlidingPagesViewController:(TTScrollSlidingPagesController *)source atIndex:(int)index
//{
//    if (index ==3){
//        return 130;
//    } else {
//        return self.view.frame.size.width;
//    }
//}

#pragma mark - delegate
-(void)didScrollToViewAtIndex:(NSUInteger)index
{
    if (index == 1) {
        //        self.tableView = self.topAppTableView.tableView;
        //        self.group = kGroupApp;
        [self appButtonPressed:nil];
    }
    else if (index == 0){
        //        self.tableView = self.topGameTableView.tableView;
        //        self.group = kGroupGame;
        [self gameButtonPressed:nil];
    }
    else {
        [self gameOnlineButtonPressed:nil];
    }
    //    [self refresh];
}


#pragma mark - GroupViewDelegate
- (void)groupView:(GroupView *)view clickAtIndex:(NSIndexPath *)indexPath {
    NSInteger index = indexPath.row * 2 + view.tag - 1;
    
    if (index < self.data.count) {
        Group* g = (Group*)[self.data objectAtIndex:index];
        [self performSelector:@selector(updateGroupView:) withObject:g afterDelay:0.0f];
        
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            
//
//            dispatch_async(dispatch_get_main_queue(), ^{
        
                MHAppListViewController* vc = [[MHAppListViewController alloc] initWithNibName:@"MHAppListViewController" bundle:nil];
                vc.listUrl = [NSString stringWithFormat:@"http://mobile.mho.vn/services/Game?IdCategoryGame=%@&IdSystem=2&IdGroup=%@&isHot=0&isNews=0&isMostView=0&pageIndex=%@&pageSize=%@&key=%@", g.groupId, groupId, @"%d", @"%d", kServerKey];
                [self.navigationController pushViewController:vc animated:YES];
//            });
//        });
    }
}

- (void)updateGroupView:(Group*)group {
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* url = [NSString stringWithFormat:@"http://www.mobile.mho.vn/services/cat?IdNhom=%@&key=%@", group.groupId, kServerKey];
    NSString* value = [ServiceLib sendGetRequest:url useCache:NO];
        NSLog(@"url: %@ value: %@", url, value);
//    });
}

- (IBAction)appButtonPressed:(id)sender {
    [self.mySlider scrollToPage:1 animated:YES];
    [self.buttonApp setEnabled:NO];
    [self.buttonGame setEnabled:YES];
    [self.buttonGameOnline setEnabled:YES];

    groupId = @"2";
    self.tableView = self.appTableView.tableView;

    if (!appFirstLoad) {
        //        firstAppRequest = YES;
        [self refresh];
    }

}
- (IBAction)gameButtonPressed:(id)sender {
    [self.mySlider scrollToPage:0 animated:YES];
    [self.buttonApp setEnabled:YES];
    [self.buttonGame setEnabled:NO];
    [self.buttonGameOnline setEnabled:YES];

    groupId = @"1";
    self.tableView = self.gameTableView.tableView;

    if (!gameFirstLoad) {
        //        firstAppRequest = YES;
        [self refresh];
    }
}
- (IBAction)gameOnlineButtonPressed:(id)sender {
    [self.mySlider scrollToPage:2 animated:YES];
    [self.buttonApp setEnabled:YES];
    [self.buttonGame setEnabled:YES];
    [self.buttonGameOnline setEnabled:NO];

    groupId = @"0";
    self.tableView = self.gameOnlineTableView.tableView;

    if (!gameOnlineFirstLoad) {
        //        firstAppRequest = YES;
        [self refresh];
    }
}
@end
